/**************************************************************************(C)*
 *
 *  This file is part of the GreenHills project
 *  Copyright (C) 2009  Tieto Corporation
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  Not for commmercial use. Only with Tieto permission.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *************************************************************************(C)*/

#include "../msgserversocketconnection.h"
#include "../msgsocketconnection.h"
#include "io/ioexception.h"

#if defined Q_OS_LINUX
    #include <sys/ioctl.h>
    #include <sys/socket.h>
    #include <netdb.h>
    #include <arpa/inet.h>
    #include <netinet/in.h>
    #include <memory.h>
#elif defined Q_OS_WIN32
#elif defined Q_OS_WINCE
#endif

#define MAX_PENDING_CONNECTIONS 10

using namespace greenhills::net;

#if defined Q_OS_LINUX
void* acceptThreadProc(void *pData)
#elif defined Q_OS_WIN32
DWORD WINAPI acceptThreadProc(void *pData)
#elif defined Q_OS_WINCE
DWORD WINAPI acceptThreadProc(void *pData)
#endif
{
    ((CMsgServerSocketConnection*)pData)->acceptNewConnections();
    return 0;
}

CMsgServerSocketConnection::CMsgServerSocketConnection()
        : mSocket(INVALID_SOCKET), mListening(true), mAcceptThread(0)
{
}

CMsgServerSocketConnection::~CMsgServerSocketConnection()
{
    stopListening();
#if defined Q_OS_WIN32 || defined Q_OS_WINCE
    WSACleanup();
#endif
}

void CMsgServerSocketConnection::listen(unsigned short pPort)
{
#if defined Q_OS_WIN32 || defined Q_OS_WINCE
    WORD versionRequested = MAKEWORD(1, 1);
    WSADATA data;

    if (WSAStartup(versionRequested, &data) != 0)
    {
        throw io::CIOException("Can't initialize socket library");
    }
#endif

    if ((mSocket = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
        throw io::CIOException("Can't create socket");
    }

    sockaddr_in addr;
    memset(&addr, 0x00, sizeof(addr));

    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = /*htonl(*/INADDR_ANY/*)*/;
    addr.sin_port = htons(pPort);

    if (bind(mSocket, (struct sockaddr*) &addr, sizeof(addr)) < 0) {
        throw io::CIOException("Can't bind local address");
    }

    if (::listen(mSocket, MAX_PENDING_CONNECTIONS) < 0) {
        throw io::CIOException("Can't listen to incoming connections");
    }

#if defined Q_OS_LINUX
    if (pthread_create(&mAcceptThread, NULL, acceptThreadProc, this) != 0)
        throw util::CException("Can't create accept thread");
#elif defined Q_OS_WIN32
    mAcceptThread = CreateThread(NULL, 0, &acceptThreadProc, this, 0, NULL);
    if (mAcceptThread == NULL)
        throw util::CException("Can't create accept thread");
#elif defined Q_OS_WINCE
    mAcceptThread = CreateThread(NULL, 0, acceptThreadProc, this, 0, NULL);
    if (mAcceptThread == NULL)
        throw util::CException("Can't create accept thread");
#endif
}

void CMsgServerSocketConnection::stopListening()
{
    if (mSocket != INVALID_SOCKET) {
#if defined Q_OS_LINUX
        shutdown(mSocket, SHUT_RDWR);
#elif defined Q_OS_WIN32
        closesocket(mSocket);
#elif defined Q_OS_WINCE
        closesocket(mSocket);
#endif
        mSocket = INVALID_SOCKET;
    }
}

bool CMsgServerSocketConnection::isListening()
{
    return mListening;
}

void CMsgServerSocketConnection::acceptNewConnections()
{
    while (isListening()) {
        struct sockaddr_in clientAddr;
        socklen_t clientAddrLength = sizeof(clientAddr);

        int socket = accept(mSocket,
                            (struct sockaddr*) &clientAddr,
                            &clientAddrLength);

        if (socket < 0) {
            throw io::CIOException("Can't accept new connection");
        }

        unsigned long mode = 1;

#if defined Q_OS_LINUX
        ioctl(socket, FIONBIO, &mode);
#elif defined Q_OS_WIN32
        ioctlsocket(socket, FIONBIO, &mode);
#elif defined Q_OS_WINCE
        ioctlsocket(socket, FIONBIO, &mode);
#endif

        CMsgSocketConnection *connection =
                new CMsgSocketConnection(socket);

        connection->addDataListener(this);

        mMutex.lock();
        mConnectionList.push_back(connection);
        mMutex.unlock();
    }
}
